package com.pierrepochon.RemoTxt.util.XML;

import java.util.ArrayList;
import java.util.Date;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

import com.pierrepochon.RemoTxt.DAO.Contact;
import com.pierrepochon.RemoTxt.DAO.SMS;
import com.pierrepochon.RemoTxt.util.Testing;

public class ParserXMLHandler extends DefaultHandler{


	private ArrayList<SMS> SMSs = new ArrayList<SMS>() ;

	private StringBuffer buffer;
	private boolean inText, inTS, inSMSs, inSMS, inDest;
	private SMS message;
	private Boolean askContact = false;
	private Boolean askMessages = false;
	
	public ParserXMLHandler() {
		super();
		SMSs = new ArrayList<SMS>();
	}
	public ArrayList<SMS> getSMSs() {
		return SMSs;
	}
	public void setSMSs(ArrayList<SMS> sMSs) {
		SMSs = sMSs;
	}
	
	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.startDocument();
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		
		if(qName.equals("SMSs"))
		{
			SMSs = new ArrayList<SMS>();
			inSMSs = true;
		}
		else if (qName.equals("SMS")) {
			message = new SMS();
			int id = Integer.parseInt(attributes.getValue("id"));
			message.setId(id);
		}

		else if (qName.equals("dest")) {
			String id = attributes.getValue("value");
			message.setNumDest(id);
		}
		else if (qName.equals("text")) {
			String txt = attributes.getValue("value");
			message.setTexte(txt);
		}
		else if (qName.equals("dh")) {
			long ts = Long.parseLong(attributes.getValue("value"));
			message.set_date(new Date(ts));
		}
		else if (qName.equals("Request")) {
			String requestName = attributes.getValue("name");
			if (requestName == "Contacts")
			{
				//demande d'envoie des contacts
				askContact = true;
			}
			else if(requestName == "Messages")
			{
				//demande d'envoie des messages
				askMessages = true;
			}
		}
		else
		{
			//erreur, on peut lever une exception
			throw new SAXException("Balise "+qName+" inconnue.");
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if(qName.equals("SMS"))
		{
			SMSs.add(message);
			message = new SMS();
		}
		super.endElement(uri, localName, qName);
	}
	public Boolean getAskContact() {
		return askContact;
	}
	public void setAskContact(Boolean askContact) {
		this.askContact = askContact;
	}
	public Boolean getAskMessages() {
		return askMessages;
	}
	public void setAskMessages(Boolean askMessages) {
		this.askMessages = askMessages;
	}
	
	
	
	
}
